﻿using Api.Common;
using Api.IRepository;
using Api.IServices;
using Api.Model.Dto.TagDto;
using Api.Model.Model;
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Api.Services
{
    public class TagServices : BaseServices<Tag, int>, ITagServices
    {
        private readonly ITagRepository _tagRepository;
        private readonly IArticleTypeRepository _articleTypeRepository;
        private readonly ITagArticleRepository _tagArticleRepository;
        private readonly IMapper _mapper;

        public TagServices(ITagRepository tagRepository,IArticleTypeRepository articleTypeRepository,ITagArticleRepository tagArticleRepository, IMapper mapper )
            : base(tagRepository)
        {
            _tagRepository = tagRepository;
            _articleTypeRepository = articleTypeRepository;
            _tagArticleRepository = tagArticleRepository;
            _mapper = mapper;
        }

        public async Task<GetTagOutput> CreateTagAsync(CreateTagInput input)
        {
            
            var tag = _mapper.Map<Tag>(input);
            await ValidateTagName(tag);
            await AddAsync(tag);
            await SaveChangesAsync();
            return _mapper.Map<GetTagOutput>(tag);
        }

        public async Task DeleteTagAsync(int id)
        {
            if (await _tagArticleRepository.AnyAsync(x=>x.TagId.Equals(id)))
            {
                throw new UIException("存在属于该标签的文章，不能删除！");
            }
            await DeleteAsync(id);
        }

        public async Task<List<Tag>> GetTagListAsync(GetTagInput input)
        {
            var query = GetALL();
            if (input.Id.HasValue)
            {
                query = query.Where(x => input.Id.Equals(x.Id));
            }
            if (!string.IsNullOrWhiteSpace(input.Name))
            {
                query = query.Where(x => x.Name.Contains(input.Name));
            }
            return await query.Include(x=>x.TagArticles).AsNoTracking().ToListAsync();
        }

        public async Task UpdateTagAsync(UpdateTagInput input)
        {

            if ((await GetByIdAsync(input.Id.Value)) is Tag tag)
            {
                
                //if (input.ImageFile != null)
                //{
                //    ReuseMethod.ImageFormatCheck(input.ImageFile.FileName);
                //    var buffer = await ReuseMethod.GetFileBufferAsync(input.ImageFile);
                //    File.WriteAllBytes(tag.Image, buffer);
                //}
                _mapper.Map(input, tag);
                await ValidateTagName(tag);
            }
        }
        public async Task ValidateTagName(Tag tag)
        {
            if (await AnyAsync(x => x.Name.Equals(tag.Name)&&!x.Id.Equals(tag.Id)))
            {
                throw new UIException("标签名称重复!");
            }
        }
    }
}
